package org.xurui.sxl.protocol.command.impl;

import org.jetlinks.core.message.CommonDeviceMessage;
import org.jetlinks.core.message.DeviceMessage;
import org.jetlinks.core.message.codec.EncodedMessage;
import org.jetlinks.core.message.codec.FromDeviceMessageContext;
import org.jetlinks.core.message.function.FunctionInvokeMessageReply;
import org.xurui.sxl.protocol.cache.ConcurrentMapCache;
import org.xurui.sxl.protocol.command.CmdCodec;
import org.xurui.sxl.protocol.enums.CommandEnum;
import org.xurui.sxl.protocol.enums.MncEnum;
import org.xurui.sxl.protocol.utils.BinaryUtils;
import org.xurui.sxl.protocol.utils.NumberUtils;
import org.xurui.sxl.protocol.utils.SxlMessageUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 要求设备上报一次 WIFI
 */
public class CmdCodec_D2 implements CmdCodec {
    @Override
    public boolean supportsCmd(String cmd) {
        return CommandEnum.D2.name().equals(cmd);
    }

    @Override
    public boolean supportsRelayCmd() {
        return true;
    }

    @Override
    public List<DeviceMessage> parsePayload(String payload, FromDeviceMessageContext context) {
        //设备回复格式：*XX,YYYYYYYYYYYYY,V4,D1,seq,HHMMSS,S,latitude,D,longitude,G,speed,pdop,MCC,MNC,TA,NUM,LAC,CID,RXLEV,Signal,SV,BAT,DDMMYY,tracker_status#
        //设备回复示例：*TJ,7893267561,V4,D1,130305,130506,V,2212.8745,N,11346.6574,E,14.28,2.8,460,00,0,1,1988,23567,0,90,00,80 ,20902,FFFFFFFF#
        FunctionInvokeMessageReply report = FunctionInvokeMessageReply.create();
        String[] payloadArr = payload.replaceAll("\\*","").split(",");
        String deviceId = payloadArr[1];
        report.setDeviceId(deviceId);
        Object messageIdObj = ConcurrentMapCache.getInstance().getAndRemove(deviceId+"_"+CommandEnum.D2.name()+"_"+payloadArr[4]);
        String messageId = messageIdObj==null?null:messageIdObj.toString();
        if(messageId==null){
            messageId = deviceId+"_"+payloadArr[4];
        }
        report.setFunctionId(CommandEnum.D2.name());
        report.setMessageId(messageId);
        report.setTimestamp(System.currentTimeMillis());
        Map<String, Object> properties = new HashMap<>();
        properties.put("uptime",payloadArr[5]);
        properties.put("s",payloadArr[6]);
        properties.put("latitude",BinaryUtils.getWgs84LonLat(payloadArr[7],"lat"));
        properties.put("d",payloadArr[8]);
        properties.put("longitude",BinaryUtils.getWgs84LonLat(payloadArr[9],"lon"));
        properties.put("g",payloadArr[10]);
        properties.put("speed", NumberUtils.parseDouble(payloadArr[11]));
        properties.put("pdop",NumberUtils.parseDouble(payloadArr[12]));

        Map ka = new HashMap();
        properties.put("ka",ka);
        ka.put("mcc","460".equals(payloadArr[13])?"中国":payloadArr[13]);//移动设备国家代码，中国 460
        String mnc = payloadArr[14];
        MncEnum mncEnum = MncEnum.matchCode(mnc);
        ka.put("mnc", mncEnum==null?mnc:mncEnum.getName());//移动设备网络代码，中国移动 = 00，中国联通 = 01,中国电信 = 11。
        ka.put("ta",payloadArr[15]);
        int kaNumber = NumberUtils.parseInt(payloadArr[16]);//数量，1-6，最多 6 个
        List<Map> kaInfo = new ArrayList<>();
        for (int i = 0; i < kaNumber; i++) {
            Map k = new HashMap();
            k.put("lac", payloadArr[17 + i * 3]);
            k.put("cellid", payloadArr[18 + i * 3]);
            k.put("rxlev", payloadArr[19 + i * 3]);
            kaInfo.add(k);
        }
        ka.put("kainfo", kaInfo);


        properties.put("signal", NumberUtils.parseInt(payloadArr[20 + (kaNumber-1) * 3]));
        properties.put("sv", NumberUtils.parseInt(payloadArr[21 + (kaNumber-1)  * 3]));
        properties.put("bat", NumberUtils.parseInt(payloadArr[22 + (kaNumber-1)  * 3]));
        properties.put("upday", payloadArr[23 + (kaNumber-1)  * 3]);
        String trackerStatusHex = payloadArr[24 + (kaNumber-1)  * 3];


        Map<String,Object> trackerStatusMap = parseTrackerStatus(trackerStatusHex);
        properties.put("trackerstatus",trackerStatusMap);
        report.setOutput(properties);
        //TODO 更新状态
        return genDeviceMessage(report);
    }

    @Override
    public EncodedMessage encodeMessage(CommonDeviceMessage message,String zzs) {
        //平台下发消息
        //格式：*XX,YYYYYYYYYYYYY,D2,HHMMSS#
        //例子：*TJ,7893267561,D2,130305#
        String time = SxlMessageUtils.getTimeHHMMSS();//DateFormatUtils.format(new Date(),"HHmmss");
        /*StringBuffer sb = new StringBuffer();
        sb.append("*");
        sb.append(zzs);//TODO 需要修改成根据设备动态加载
        sb.append(",");
        sb.append(message.getDeviceId());
        sb.append(",");
        sb.append(CommandEnum.D2.name());
        sb.append(",");
        sb.append(time);
        sb.append("#");*/
        ConcurrentMapCache.getInstance().set(message.getDeviceId()+"_"+CommandEnum.D2.name()+"_"+time,message.getMessageId(),60*3*1000);
        //messageIdMap.put(message.getDeviceId()+"_"+time,message.getMessageId());
        //return EncodedMessage.simple(Unpooled.wrappedBuffer(sb.toString().getBytes()));
        return SxlMessageUtils.SxlCmd.getInstance()
            .appendAndAddSeparator(zzs)
            .appendAndAddSeparator(message.getDeviceId())
            .appendAndAddSeparator(CommandEnum.D2.name())
            .append(time).buildEncodeMessage();
    }
}
